package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
 @Autowired
 private RoleDao roleDao;

 @Override
 public List<Role> findAll() {
  return roleDao.findAll();
 }

 @Override
 public PageResult findPage(QueryPageBean pageBean) {
  PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
  Page<Role> page = roleDao.findByCondition(pageBean.getQueryString());
  return new PageResult(page.getTotal(), page);
 }

 //和权限、菜单关联
 @Override
 public void add(Role role, Integer[] permissionIds, Integer[] menuIds) {
  roleDao.add(role);
  //权限关联
  setRelation(role.getId(), permissionIds, "permission");
  //菜单关联
  setRelation(role.getId(), menuIds, "menu");
 }

 @Override
 public Role findById(Integer id) {
  return roleDao.findById(id);
 }

 @Override
 public List<Integer> findPermissionIdsByRoleId(Integer roleId) {
  return roleDao.findPermissionIdsByRoleId(roleId);
 }

 @Override
 public List<Integer> findMenuIdsByRoleId(Integer roleId) {
  return roleDao.findMenuIdsByRoleId(roleId);
 }

 @Override
 public void edit(Role role, Integer[] permissionIds, Integer[] menuIds) {
  //删除所有的关系权限和菜单
  roleDao.delRelationPer(role.getId());
  roleDao.delRelationMenu(role.getId());
  //维护新的关系
  //权限
  setRelation(role.getId(), permissionIds, "permission");
  //菜单
  setRelation(role.getId(), menuIds, "menu");
  //编辑角色
  roleDao.edit(role);
 }

 @Override
 public void delById(Integer id) {
  //判断有无user关联
  long count = roleDao.findCountById(id);
  if (count > 0) {
   throw new BusinessRuntimeException("该角色被用户关联，不能删除！！");
  }
  //判断有无permission关联
  long number = roleDao.findCountById2(id);
  if (count > 0) {
   throw new BusinessRuntimeException("该角色被权限关联，不能删除！！");
  }
  //删除关联的两张表
  roleDao.delRelationPer(id);
  roleDao.delRelationMenu(id);
  //删除角色
  roleDao.delById(id);
 }

 //设置角色和权限、菜单的关联关系
 private void setRelation(Integer roleId, Integer[] Ids, String kind) {
  if (Ids != null && Ids.length > 0) {
   //对权限进行判断
   if ("permission".equals(kind)) {
    for (Integer Id : Ids) {
     roleDao.setRelationPer(roleId, Id);
    }
   }
   //对菜单进行判断
   if ("menu".equals(kind)) {
    for (Integer Id : Ids) {
     roleDao.setRelationMenu(roleId, Id);
    }
   }
  }
 }
}
